import GUI from "lil-gui";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import Stats from "three/examples/jsm/libs/stats.module";

class Gui {
  lightY: number; //灯光y轴的位置
  cubeY: number; //球的z轴的位置
  cubeX: number; //立方体的x轴位置
  cubeZ: number; //立方体的z轴的位置
  // 构造函数
  constructor(lightY = 30, cubeX = 0, cubeY = 0, cubeZ = 0) {
    this.lightY = lightY;
    this.cubeX = cubeX;
    this.cubeY = cubeY;
    this.cubeZ = cubeZ;
  }
}

export default class ThreeJs {
  gui: Gui | null = null;
  stats: Stats | null = null;
  scene: THREE.Scene | null = null;
  camera: THREE.PerspectiveCamera | null = null;
  light: THREE.PointLight | null = null;
  renderer: THREE.WebGLRenderer | null = null;
  ambientLight: THREE.AmbientLight | null = null;
  cube: THREE.Mesh | null = null;
  controls: OrbitControls | null = null;

  constructor() {
    this.init();
  }

  init(): void {
    this.initGui();
    this.initRender();
    this.initScene();
    this.initCamera();
    this.initLight();
    this.initModel();
    this.initControls();
    this.initStats();
    this.animate();
    this.onWindowResize();
  }

  onWindowResize(): void {
    window.addEventListener("resize", () => {
      if (this.camera && this.renderer) {
        this.camera.aspect = window.innerWidth / window.innerHeight;
        this.camera.updateProjectionMatrix();
        this.render();
        this.renderer.setSize(window.innerWidth, window.innerHeight);
      }
    });
  }

  initGui(): void {
    //声明一个保存需求修改的相关数据的对象
    this.gui = new Gui();
    const datGui = new GUI();
    //将设置属性添加到gui当中，gui.add(对象，属性，最小值，最大值）
    datGui.add(this.gui, "lightY", 0, 100);
    datGui.add(this.gui, "cubeX", -30, 30);
    datGui.add(this.gui, "cubeY", -30, 30);
    datGui.add(this.gui, "cubeZ", -30, 30);
  }

  initScene(): void {
    this.scene = new THREE.Scene();
  }

  // 新建透视相机
  initCamera(): void {
    // 第二参数就是 长度和宽度比 默认采用浏览器  返回以像素为单位的窗口的内部宽度和高度
    this.camera = new THREE.PerspectiveCamera(
      45,
      window.innerWidth / window.innerHeight,
      0.1,
      1000
    );
    this.camera.position.set(0, 40, 100);
    this.camera.lookAt(new THREE.Vector3(0, 0, 0));
  }

  // 设置渲染器
  initRender(): void {
    this.renderer = new THREE.WebGLRenderer({ antialias: true });
    // 设置画布的大小
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    //告诉渲染器需要阴影效果
    this.renderer.shadowMap.enabled = true;
    this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; // 默认的是，没有设置的这个清晰 THREE.PCFShadowMap
    //这里 其实就是canvas 画布  renderer.domElement
    document.body.appendChild(this.renderer.domElement);
  }

  // 设置环境光
  initLight(): void {
    this.scene && this.scene.add(new THREE.AmbientLight(0x444444));
    this.light = new THREE.PointLight(0xffffff);
    this.light.position.set(15, 30, 10);
    //告诉平行光需要开启阴影投射
    this.light.castShadow = true;
    this.scene && this.scene.add(this.light);
  }

  // 创建网格模型
  initModel(): void {
    if (this.scene) {
      //辅助工具
      const helper = new THREE.AxesHelper(10);
      this.scene.add(helper);

      const geometry = new THREE.BufferGeometry();
      const vertices = new Float32Array([0, 0, 20, 20, 0, 0, 0, 40, 0]);

      // itemSize = 3 因为每个顶点都是一个三元组。
      geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));
      const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
      this.cube = new THREE.Mesh(geometry, material);

      this.scene.add(this.cube);

      // 三角形的三个点坐标p1，p2，p3，p4
      const p1 = new THREE.Vector3(0, 0, 20); // 点1坐标
      const p2 = new THREE.Vector3(20, 0, 0); // 点2坐标
      const p3 = new THREE.Vector3(0, 40, 0); // 点3坐标
      const p4 = new THREE.Vector3(20, 40, 0); // 点4坐标

      // p1，p2两个点确定一个向量
      const v1 = p1.clone().sub(p2);
      // p1，p3两个点确定一个向量
      const v2 = p1.clone().sub(p3);
      // .dot()计算两个向量点积    .length()计算向量长度
      // 返回三角形顶点p1对应夹角余弦值
      const CosineValue = v1.dot(v2) / (v1.length() * v2.length());
      console.log("三角形两条边夹角余弦值", CosineValue);
      // .acos()：反余弦函数，返回结果是弧度
      console.log("三角形两条边夹角", (Math.acos(CosineValue) * 180) / Math.PI);
      const areaOfTriangle = this.areaOfTriangle(p1, p2, p3);
      console.log(areaOfTriangle);
      const areaOfCuboid = this.areaOfCuboid(p1, p2, p3, p4);
      console.log(areaOfCuboid);
    }
  }

  //三角形面积计算
  areaOfTriangle(
    p1: THREE.Vector3,
    p2: THREE.Vector3,
    p3: THREE.Vector3
  ): number {
    let v1 = new THREE.Vector3();
    let v2 = new THREE.Vector3();
    // 通过两个顶点坐标计算其中两条边构成的向量
    v1 = p1.clone().sub(p2);
    v2 = p1.clone().sub(p3);

    const v3 = new THREE.Vector3();
    // 三角形面积计算
    v3.crossVectors(v1, v2);
    const s = v3.length() / 2;
    return s;
  }

  // 长方形
  areaOfCuboid(
    p1: THREE.Vector3,
    p2: THREE.Vector3,
    p3: THREE.Vector3,
    p4: THREE.Vector3
  ): number {
    let v1 = new THREE.Vector3();
    let v2 = new THREE.Vector3();
    let v3 = new THREE.Vector3();
    let v4 = new THREE.Vector3();
    // 通过两个顶点坐标计算其中两条边构成的向量
    v1 = p1.clone().sub(p2);
    v2 = p1.clone().sub(p3);
    v3 = p4.clone().sub(p2);
    v4 = p4.clone().sub(p3);

    const v5 = new THREE.Vector3();
    const v6 = new THREE.Vector3();
    // 三角形面积计算
    v5.crossVectors(v1, v2);
    v6.crossVectors(v3, v4);
    console.log(v5, v6);
    const s1 = v5.length() / 2;
    const s2 = v6.length() / 2;
    return s1 + s2;
  }

  // 渲染
  render(): void {
    if (this.renderer && this.scene && this.camera) {
      this.renderer.render(this.scene, this.camera);
    }
  }

  // 动画
  animate(): void {
    //更新控制器
    this.render();

    //更新性能插件
    this.stats && this.stats.update();

    //更新相关位置
    if (this.gui) {
      if (this.light) {
        this.gui.lightY && (this.light.position.y = this.gui.lightY);
      }
      if (this.cube) {
        // this.cube.rotation.y += 0.01;
        this.gui.cubeX && (this.cube.position.x = this.gui.cubeX);
        this.gui.cubeY && (this.cube.position.y = this.gui.cubeY);
        this.gui.cubeZ && (this.cube.position.z = this.gui.cubeZ);
      }
    }

    this.controls && this.controls.update();

    requestAnimationFrame(this.animate.bind(this));
  }

  initControls(): void {
    if (this.camera && this.renderer) {
      this.controls = new OrbitControls(this.camera, this.renderer.domElement);

      // 如果使用animate方法时，将此函数删除
      //this.controls.addEventListener( 'change', render );
      // 使动画循环使用时阻尼或自转 意思是否有惯性
      this.controls.enableDamping = true;
      //动态阻尼系数 就是鼠标拖拽旋转灵敏度
      //controls.dampingFactor = 0.25;
      //是否可以缩放
      this.controls.enableZoom = true;
      //是否自动旋转
      this.controls.autoRotate = false;
      //设置相机距离原点的最远距离
      this.controls.minDistance = 100;
      //设置相机距离原点的最远距离
      this.controls.maxDistance = 200;
      //是否开启右键拖拽
      this.controls.enablePan = true;
    }
  }

  initStats(): void {
    this.stats = Stats();
    document.body.appendChild(this.stats.dom);
  }
}
